<template>
	<view class="container">
		<!-- 头部导航 -->
		<page-navbar title="我的订单"></page-navbar>

		<!-- 分段器 -->
		<view class="segmented-control-container">
			<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" styleType="text"
				activeColor="#2E7D32"></uni-segmented-control>
		</view>

		<!-- 订单列表 -->
		<scroll-view class="order-list-container" scroll-y="true" @scrolltolower="loadMore">
			<!-- 订单列表 -->
			<view class="order-list" v-if="orderList.length > 0">
				<view class="order-item" v-for="order in orderList" :key="order.id">
					<!-- 订单头部 -->
					<view class="order-header">
						<view class="order-info">
							<text class="order-number">订单号：{{ order.id }}</text>
							<text class="order-time">{{ formatTime(order.created_at) }}</text>
						</view>
						<view class="order-status" :class="getStatusClass(order.order_status)">
							<text class="status-text">{{ getStatusText(order.order_status) }}</text>
						</view>
					</view>

					<!-- 商品信息 -->
					<view class="product-section" @click="goToOrderDetail(order)">
						<image class="product-image" :src="common.defaultImg(order.commdities?.[0]?.photo)"
							mode="aspectFill">
						</image>
						<view class="product-details">
							<text class="product-name">{{ order.commdities?.[0]?.commodity_name }}</text>
							<view class="product-specs"
								v-if="order.commdities?.[0]?.commodity_spec && order.commdities?.[0]?.commodity_unit">
								<text class="specs-text">{{ order.commdities?.[0]?.commodity_spec + " / " +
									order.commdities?.[0]?.commodity_unit }}</text>
							</view>
							<view class="product-price-info">
								<text class="product-price">¥{{ computedPrice(order.commdities?.[0]) }}</text>
								<text class="product-quantity">x{{ order.commdities?.[0]?.quantity }}</text>
							</view>
						</view>
					</view>

					<!-- 订单金额 -->
					<view class="order-amount">
						<view class="amount-detail">
							<text class="amount-label">商品金额：</text>
							<text class="amount-value">¥{{ computedPriceAll(order.commdities?.[0]) }}</text>
						</view>
						<view class="amount-detail" v-if="order.minus_amount > 0">
							<text class="amount-label">优惠减免：</text>
							<text class="amount-value discount">-¥{{ order.minus_amount }}</text>
						</view>
						<view class="amount-total">
							<text class="total-label">实付金额：</text>
							<text class="total-value">¥{{ order.actual_amount }}</text>
						</view>
					</view>

					<!-- 订单操作 -->
					<view class="order-actions">
						<view class="action-left">
							<text class="payment-method">{{ getPaymentMethodText(order.payment_method) }}</text>
						</view>
						<view class="action-buttons">
							<!-- 待付款状态 -->
							<view class="action-btn cancel-btn" v-if="order.order_status == 1"
								@click="cancelOrder(order)">
								<text class="btn-text">取消订单</text>
							</view>
							<view class="action-btn primary-btn" v-if="order.order_status == 1"
								@click="payOrder(order)">
								<text class="btn-text">立即付款</text>
							</view>

							<!-- 待发货状态 -->
							<view class="action-btn" v-if="order.order_status == 2 || order.order_status == 3"
								@click="contactMerchant(order)">
								<text class="btn-text">联系商家</text>
							</view>

							<!-- 待收货状态 -->
							<view class="action-btn" v-if="order.order_status == 2 || order.order_status == 3"
								@click="checkLogistics(order)">
								<text class="btn-text">查看物流</text>
							</view>
							<view class="action-btn primary-btn" v-if="order.order_status == 3"
								@click="confirmReceive(order)">
								<text class="btn-text">确认收货</text>
							</view>

							<!-- 已完成状态 -->
							<view class="action-btn" v-if="order.order_status == 4" @click="buyAgain(order)">
								<text class="btn-text">再次购买</text>
							</view>
							<view class="action-btn" v-if="order.order_status == 4" @click="evaluateOrder(order)">
								<text class="btn-text">评价商品</text>
							</view>

							<!-- 已取消状态 -->
							<view class="action-btn" v-if="order.order_status == 5" @click="deleteOrder(order)">
								<text class="btn-text">删除订单</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 空状态 -->
			<view class="empty-state" v-else>
				<image class="empty-image" src="/static/images/empty-order.svg" mode="aspectFit"></image>
				<text class="empty-text">暂无订单</text>
				<view class="empty-btn" @click="goToShopping">
					<text class="empty-btn-text">去购物</text>
				</view>
			</view>

			<!-- 加载更多 -->
			<view class="load-more" v-if="hasMore && orderList.length > 0">
				<text class="load-text">加载更多...</text>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick, toRefs } from 'vue';
import { onLoad, onShow, onShareAppMessage } from '@dcloudio/uni-app';
import api from '@/api/index.js';
import common from '@/utils/common.js';

import dayjs from 'dayjs';

const current = ref(0);
const items = ref(['全部订单', '待付款', '待发货', '待收货', '已完成', '已取消']);

const orderList = ref([]);
const hasMore = ref(true);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);

onLoad((options) => {
	current.value = Number(options.type) || 0
})

onShow(() => {
	getList();
});

onMounted(() => { });

// 单价
const computedPrice = (item) => {
	if (item.discount) {
		return (item.price * item.discount).toFixed(2);
	}
	return item.price.toFixed(2);
}
// 单价
const computedPriceAll = (item) => {
	if (item.discount) {
		return (item.price * item.discount * item.quantity).toFixed(2);
	}
	return (item.price * item.quantity).toFixed(2);
}
const formatTime = (time) => {
	return dayjs(time).format('YYYY-MM-DD HH:mm');
}

const getList = () => {
	api.commerceApi.orderList({
		page: page.value,
		pageSize: pageSize.value,
		// 订单状态：1-未支付，2-待发货，3-待收货，4-已完成，5-已取消，6-已删除
		order_status: current.value === 0 ? null : current.value

	}).then(res => {
		console.log("订单列表", res);
		if (page.value == 1) {
			orderList.value = res.list || [];
		} else {
			orderList.value = [...orderList.value, ...(res.list || [])];
		}
		total.value = res.total;
		hasMore.value = orderList.value.length < total.value;
	})
}

// 获取订单状态文本
const getStatusText = (status) => {
	const statusMap = {
		1: '待付款',
		2: '待发货',
		3: '待收货',
		4: '已完成',
		5: '已取消'
	};
	return statusMap[status] || '未知状态';
};

// 获取订单状态样式类
const getStatusClass = (status) => {
	const classMap = {
		1: 'status-pending',
		2: 'status-processing',
		3: 'status-shipping',
		4: 'status-completed',
		5: 'status-cancelled'
	};
	return classMap[status] || '';
};

// 获取支付方式文本
const getPaymentMethodText = (method) => {
	const methodMap = {
		1: '银行转账',
		2: '微信支付',
		3: '支付宝支付',
		4: '现金支付',
		5: '其他方式'
	};
	return methodMap[method] || '未知支付方式';
};

const onClickItem = e => {
	if (current.value !== e.currentIndex) {
		current.value = e.currentIndex;
		page.value = 1;
		hasMore.value = true;
		getList();
	}
};

// 加载更多
const loadMore = () => {
	if (hasMore.value) {
		page.value++;
		getList();
	}
};

// 跳转到订单详情
const goToOrderDetail = (order) => {
	uni.navigateTo({
		url: `/pages/commerce/detail?id=${order.commdities[0]?.commodity_id}`
	});
};

// 取消订单
const cancelOrder = (order) => {
	uni.showModal({
		title: '确认取消',
		content: '确定要取消这个订单吗？',
		success: (res) => {
			if (res.confirm) {
				api.commerceApi.cancelOrder({
					id: order.id
				}).then(res => {
					uni.showToast({
						title: '订单已取消',
						icon: 'success'
					});
					getList();
				})
			}
		}
	});
};

// 立即付款
const payOrder = (order) => {
	// uni.navigateTo({
	// 	url: `/pages/commerce/purchase?orderId=${order.id}`
	// });
};

// 联系商家
const contactMerchant = (order) => {
	uni.showActionSheet({
		itemList: ['拨打电话', '复制号码'],
		success: (res) => {
			if (res.tapIndex === 0) {
				uni.makePhoneCall({
					phoneNumber: order.merchant?.contact_phone || ''
				});
			} else if (res.tapIndex === 1) {
				uni.setClipboardData({
					data: order.merchant?.contact_phone || '',
					success: () => {
						uni.showToast({
							title: '号码已复制',
							icon: 'success'
						});
					}
				});
			}
		}
	});
};

// 查看物流
const checkLogistics = (order) => {
	uni.showToast({
		title: '功能开发中',
		icon: 'none'
	});
	// uni.navigateTo({
	// 	url: `/pages/commerce/logistics?orderNumber=${order.order_number}`
	// });
};

// 确认收货
const confirmReceive = (order) => {
	uni.showModal({
		title: '确认收货',
		content: '确认已收到商品吗？',
		success: (res) => {
			if (res.confirm) {
				uni.showToast({
					title: '收货成功',
					icon: 'success'
				});
			}
		}
	});
};

// 再次购买
const buyAgain = (order) => {
	uni.navigateTo({
		url: `/pages/commerce/detail?id=${order.commdities[0]?.commodity_id}`
	});
};

// 评价商品
const evaluateOrder = (order) => {
	uni.showToast({
		title: '功能开发中',
		icon: 'none'
	});
	// uni.navigateTo({
	// 	url: `/pages/commerce/evaluate?orderId=${order.commdities[0]?.commodity_id}`
	// });
};

// 删除订单
const deleteOrder = (order) => {
	uni.showModal({
		title: '确认删除',
		content: '确定要删除这个订单吗？删除后无法恢复。',
		success: (res) => {
			if (res.confirm) {
				api.commerceApi.delOrder({
					id: order.id
				}).then(res => {
					uni.showToast({
						title: '订单已删除',
						icon: 'success'
					});
					getList();
				})
			}
		}
	});
};

// 去购物
const goToShopping = () => {
	uni.redirectTo({
		url: '/pages/commerce/commodity'
	});
};

</script>

<style lang="scss" scoped>
.container {
	background-color: #f2f1f6;
	height: 100vh;
	width: 100vw;
	display: flex;
	flex-direction: column;
}

.segmented-control-container {
	background-color: #fff;
	padding: 10rpx 0;
}

.order-list-container {
	flex: 1;
	overflow: hidden;
	padding: 20rpx;
	box-sizing: border-box;
}

.order-list {
	.order-item {
		background: white;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
		overflow: hidden;

		.order-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx;
			border-bottom: 1rpx solid #f0f0f0;

			.order-info {
				.order-number {
					font-size: 28rpx;
					color: #333;
					display: block;
					margin-bottom: 10rpx;
				}

				.order-time {
					font-size: 24rpx;
					color: #999;
				}
			}

			.order-status {
				.status-text {
					font-size: 28rpx;
					font-weight: 500;
				}

				&.status-pending .status-text {
					color: #FF6B35;
				}

				&.status-processing .status-text {
					color: #2E7D32;
				}

				&.status-shipping .status-text {
					color: #1976D2;
				}

				&.status-completed .status-text {
					color: #388E3C;
				}

				&.status-cancelled .status-text {
					color: #757575;
				}
			}
		}

		.product-section {
			display: flex;
			padding: 30rpx;
			border-bottom: 1rpx solid #f0f0f0;

			.product-image {
				width: 120rpx;
				height: 120rpx;
				border-radius: 12rpx;
				margin-right: 20rpx;
			}

			.product-details {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.product-name {
					font-size: 30rpx;
					color: #333;
					line-height: 1.4;
					margin-bottom: 10rpx;
				}

				.product-specs {
					.specs-text {
						font-size: 24rpx;
						color: #999;
						background: #f5f5f5;
						padding: 4rpx 12rpx;
						border-radius: 6rpx;
					}
				}

				.product-price-info {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 10rpx;

					.product-price {
						font-size: 32rpx;
						color: #FF6B35;
						font-weight: 600;
					}

					.product-quantity {
						font-size: 28rpx;
						color: #666;
					}
				}
			}
		}

		.order-amount {
			padding: 20rpx 30rpx;
			border-bottom: 1rpx solid #f0f0f0;

			.amount-detail {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 8rpx;

				.amount-label {
					font-size: 26rpx;
					color: #666;
				}

				.amount-value {
					font-size: 26rpx;
					color: #333;

					&.discount {
						color: #FF6B35;
					}
				}
			}

			.amount-total {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 10rpx;

				.total-label {
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
				}

				.total-value {
					font-size: 32rpx;
					color: #FF6B35;
					font-weight: 600;
				}
			}
		}

		.order-actions {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx;

			.action-left {
				.payment-method {
					font-size: 26rpx;
					color: #666;
				}
			}

			.action-buttons {
				display: flex;
				gap: 20rpx;

				.action-btn {
					padding: 12rpx 24rpx;
					border: 1rpx solid #ddd;
					border-radius: 8rpx;
					background: white;

					.btn-text {
						font-size: 26rpx;
						color: #666;
					}

					&.primary-btn {
						background: #2E7D32;
						border-color: #2E7D32;

						.btn-text {
							color: white;
						}
					}

					&.cancel-btn {
						border-color: #FF6B35;

						.btn-text {
							color: #FF6B35;
						}
					}
				}
			}
		}
	}
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;

	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 40rpx;
	}

	.empty-text {
		font-size: 32rpx;
		color: #999;
		margin-bottom: 40rpx;
	}

	.empty-btn {
		background: #2E7D32;
		padding: 20rpx 40rpx;
		border-radius: 8rpx;

		.empty-btn-text {
			font-size: 28rpx;
			color: white;
		}
	}
}

.load-more {
	text-align: center;
	padding: 40rpx 0;

	.load-text {
		font-size: 28rpx;
		color: #999;
	}
}
</style>
